package com.qianyitian.hope2.spider.gaokao;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Files;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class DataMerger {
    Map<String, OneFenOneDuan> likeMap;
    Map<String, OneFenOneDuan> wenkeMap;


    public DataMerger() throws IOException {
        {
            File file = new File("2021-like.json");
            String line = Files.asCharSource(file, Charset.forName("UTF-8")).read();
            List<OneFenOneDuan> list = JSON.parseArray(line, OneFenOneDuan.class);
            likeMap = list.stream().collect(Collectors.toMap(OneFenOneDuan::getScore, Function.identity()));
        }

        {
            File file = new File("2021-wenke.json");
            String line = Files.asCharSource(file, Charset.forName("UTF-8")).read();
            List<OneFenOneDuan> list = JSON.parseArray(line, OneFenOneDuan.class);
            wenkeMap = list.stream().collect(Collectors.toMap(OneFenOneDuan::getScore, Function.identity()));
        }


    }

    public void readBoth() throws IOException {
        File file1 = new File("辽宁省投档分-like.csv");
        read(file1, "2021-tidang-like.json", likeMap);

        File file2 = new File("辽宁省投档分-wenke.csv");
        read(file2, "2021-tidang-wenke.json", wenkeMap);
    }

    private String read(File file, String tofile, Map<String, OneFenOneDuan> map) throws IOException {

        ImmutableList<String> list = Files.asCharSource(file, Charset.forName("UTF-8")).readLines();

        List all = new ArrayList();

        for (String row : list) {
            String[] array = row.split(",");
            TouDang tou = new TouDang();
            tou.setCollegeId(array[0]);
            tou.setCollege(array[1]);
            tou.setMajorId(array[2]);
            tou.setMajor(array[3]);


            String score = array[4];
            tou.setScore(Integer.valueOf(score));

            tou.setPosition(getPosition(score, map));

            all.add(tou);
        }
        String result = JSON.toJSONString(all, true);
        File to = new File(tofile);
        Files.asCharSink(to, Charset.forName("UTF-8")).write(result);
        return result;
    }

    public Integer getPosition(String score, Map<String, OneFenOneDuan> map) {
        int i = Integer.valueOf(score);
        if (i > 710) {
            return -1;
        }

        OneFenOneDuan oneFenOneDuan = map.get(score);
        if (oneFenOneDuan != null) {
            return oneFenOneDuan.getPosition();
        }
        i++;

        return getPosition(String.valueOf(i), map);
    }
}
